# -*- coding: utf-8 -*-
"""
@Author: thekernel
@Date: 2020/6/28 20:17
@Description: 京东爬虫 工具类
"""
import requests
import json
import re
import random


def get_ware_id(url: str):
    pattern = r"https://item.jd.com/(\w+).html"
    data = re.findall(pattern, url)

    return data[0]


def get_price(ware_id: str):
    price_url = "http://p.3.cn/prices/mgets?skuIds={}&pin=null&pduid=" + str(random.randint(100000, 999999))
    while True:
        try:
            text = requests.get(price_url.format(ware_id)).text
            if text is None:
                continue
            data = json.loads(text)
            break
        except requests.exceptions.ConnectionError:
            continue
    return data[0].get("p")


def get_comment_num(ware_id: str):
    comment_url = "https://club.jd.com/comment/productPageComments.action" \
                  "?productId={}&score=0&sortType=5&page=0&pageSize=10"
    text = requests.get(comment_url.format(ware_id)).text
    if text is None or text == "":
        comment_url = "https://club.jd.com/comment/productCommentSummaries.action?referenceIds={}"
        text = requests.get(comment_url.format(ware_id)).text
        data = json.loads(text)
        comments_count = data["CommentsCount"][0]
        return comments_count["CommentCount"], comments_count["GoodCount"]
    data = json.loads(text)
    product_comment_summary = data["productCommentSummary"]
    return product_comment_summary["commentCount"], product_comment_summary["goodCount"]
